package com.ordobill.webapp.filter;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.commons.logging.*;
import com.ordobill.webapp.common.Constants;
import com.ordobill.webapp.exception.*;

public class ValidateSessionFilter implements Filter {
	 
	private Log log = LogFactory.getFactory().getInstance(this.getClass().getName());
	
	private FilterConfig config = null;
	private String[] patterns = null;
	
	public void init(FilterConfig config) throws ServletException {
		this.config = config;
		
		String param = config.getInitParameter("url-pattern-exclude");
		if (param != null)
			patterns = param.split(",");
		
		log.debug("url-pattern-exclude : " + param);
	}

	public void doFilter(ServletRequest request, 
			             ServletResponse response, 
			             FilterChain chain) 
	throws IOException, ServletException {
		
		if (config == null)	return;
		
		HttpServletRequest req = (HttpServletRequest) request;		
		HttpSession session = req.getSession();
		
		String path = req.getServletPath();
		log.debug("req.getServletPath() : " + path);		
		request.setAttribute("action", path);

		try {
			if (isNormalURLPattern(path)) {
				log.debug("session.isNew() : " + session.isNew());
				log.debug("session.getAttribute('" + Constants.SESSION_UNIT_OK + "') : " 
						+ (session.getAttribute(Constants.SESSION_UNIT_OK) == null));
				if (!session.isNew() && session.getAttribute(Constants.SESSION_UNIT_OK) == null)
					throw new NoSessionException("세션이 종료되었습니다.");
			}
			
			log.debug("session is alive!!!");
			chain.doFilter(request, response);			
			
		} catch (NoSessionException nse) {
			log.debug("session is dead!!!");
			
			HttpServletResponse res = (HttpServletResponse) response;
			res.sendRedirect("no-session.do");
		}
	}
	
	private boolean isNormalURLPattern(String path) {
		
		boolean result = true;
		
		if (patterns != null) {
			for (int i = 0; i < patterns.length; i++) {
				if (patterns[i].trim().equals(path)) {					
					result = false;
					log.debug("patterns[" + i + "] " + patterns[i].trim() + " : " + result);
					break;
				}
			}
		}
		
		return result;
	}
	
	public void destroy() {
		config = null;
	}
}
